// src/pages/user/password/forgot/index.tsx
import { SmsTypeEnum } from '@/enums/auth';
import { submit } from '@/services/data';
import { LockOutlined, MobileOutlined } from '@ant-design/icons';
import { FormattedMessage, history, useIntl } from '@umijs/max';
import { Alert, Button, Form, Input, message, Steps, Typography } from 'antd';
import React, { useState } from 'react';
import useStyles from './style';

const { Title, Text } = Typography;

const Index: React.FC = () => {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);
  const [success] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [phoneNumber, setPhoneNumber] = useState('');
  const intl = useIntl();
  const { styles } = useStyles();

  const steps = [
    {
      title: intl.formatMessage({
        id: 'pages.forgotPassword.steps.phone',
        defaultMessage: '输入手机号',
      }),
    },
    {
      title: intl.formatMessage({
        id: 'pages.forgotPassword.steps.captchaAndPassword',
        defaultMessage: '重置密码',
      }),
    },
    {
      title: intl.formatMessage({
        id: 'pages.forgotPassword.steps.success',
        defaultMessage: '完成',
      }),
    },
  ];

  const handleSendCaptcha = async (phone: string) => {
    const res: any = await submit('/system/index/sendCaptcha', {
      phone,
      smsCode: SmsTypeEnum.FORGET_PASSWORD,
    });
    if (!res.success) {
      message.error(
        intl.formatMessage({
          id: 'pages.forgotPassword.captcha.send.failed',
          defaultMessage: '验证码发送失败，请稍后重试',
        }),
      );
      return;
    }
    setPhoneNumber(phone);
    setCurrentStep(1);
    message.success(
      intl.formatMessage({
        id: 'pages.forgotPassword.captcha.sent',
        defaultMessage: '验证码已发送至您的手机',
      }),
    );
  };

  const handleVerifyAndReset = async (values: {
    phone: string;
    captcha: string;
    password: string;
    confirmPassword: string;
  }) => {
    const { phone, captcha, password, confirmPassword } = values;
    if (password !== confirmPassword) {
      message.error(
        intl.formatMessage({
          id: 'pages.forgotPassword.password.mismatch',
          defaultMessage: '两次输入的密码不一致',
        }),
      );
      return;
    }
    setSubmitting(true);

    const res: any = await submit('/system/index/verifyCaptcha', {
      phone,
      captcha,
      password,
      smsCode: 1,
    });
    setSubmitting(false);

    if (!res.success) {
      message.error(res.msg);
      return;
    }
    message.success(
      intl.formatMessage({
        id: 'pages.forgotPassword.captcha.verified',
        defaultMessage: '身份验证成功',
      }),
    );
    setCurrentStep(2);
  };

  const renderStep0 = () => (
    <Form form={form} onFinish={(values) => handleSendCaptcha(values.phone)}>
      <Form.Item
        name="phone"
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="pages.forgotPassword.phone.required"
                defaultMessage="请输入手机号！"
              />
            ),
          },
          {
            pattern: /^1\d{10}$/,
            message: (
              <FormattedMessage
                id="pages.forgotPassword.phone.invalid"
                defaultMessage="手机号格式错误！"
              />
            ),
          },
        ]}
      >
        <Input
          prefix={<MobileOutlined />}
          placeholder={intl.formatMessage({
            id: 'pages.forgotPassword.phone.placeholder',
            defaultMessage: '请输入手机号',
          })}
          size="large"
        />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" block size="large">
          <FormattedMessage id="pages.forgotPassword.next" defaultMessage="下一步" />
        </Button>
      </Form.Item>
    </Form>
  );

  const renderStep1 = () => (
    <Form form={form} onFinish={handleVerifyAndReset}>
      <Form.Item
        name="phone"
        initialValue={phoneNumber}
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="pages.forgotPassword.phone.required"
                defaultMessage="请输入手机号！"
              />
            ),
          },
        ]}
      >
        <Input
          prefix={<MobileOutlined />}
          placeholder={intl.formatMessage({
            id: 'pages.forgotPassword.phone.placeholder',
            defaultMessage: '请输入手机号',
          })}
          disabled
          size="large"
        />
      </Form.Item>

      <Form.Item
        name="captcha"
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="pages.forgotPassword.captcha.required"
                defaultMessage="请输入验证码！"
              />
            ),
          },
        ]}
      >
        <Input
          prefix={<LockOutlined />}
          placeholder={intl.formatMessage({
            id: 'pages.forgotPassword.captcha.placeholder',
            defaultMessage: '请输入验证码',
          })}
          size="large"
        />
      </Form.Item>

      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="pages.forgotPassword.password.required"
                defaultMessage="请输入新密码！"
              />
            ),
          },
          {
            min: 6,
            message: (
              <FormattedMessage
                id="pages.forgotPassword.password.min"
                defaultMessage="密码至少6位"
              />
            ),
          },
        ]}
      >
        <Input.Password
          prefix={<LockOutlined />}
          placeholder={intl.formatMessage({
            id: 'pages.forgotPassword.password.placeholder',
            defaultMessage: '请输入新密码',
          })}
          size="large"
        />
      </Form.Item>

      <Form.Item
        name="confirmPassword"
        rules={[
          {
            required: true,
            message: (
              <FormattedMessage
                id="pages.forgotPassword.confirmPassword.required"
                defaultMessage="请确认新密码！"
              />
            ),
          },
        ]}
      >
        <Input.Password
          prefix={<LockOutlined />}
          placeholder={intl.formatMessage({
            id: 'pages.forgotPassword.confirmPassword.placeholder',
            defaultMessage: '请再次输入新密码',
          })}
          size="large"
        />
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" loading={submitting} block size="large">
          <FormattedMessage
            id="pages.forgotPassword.verifyAndReset"
            defaultMessage="验证并重置密码"
          />
        </Button>
      </Form.Item>

      <div style={{ textAlign: 'center' }}>
        <Button type="link" onClick={() => handleSendCaptcha(phoneNumber)}>
          <FormattedMessage
            id="pages.forgotPassword.captcha.resend"
            defaultMessage="重新发送验证码"
          />
        </Button>
      </div>
    </Form>
  );
  const renderStep2 = () => (
    <div style={{ textAlign: 'center' }}>
      <Alert
        message={
          <FormattedMessage id="pages.forgotPassword.reset.success" defaultMessage="密码重置成功" />
        }
        description={
          <FormattedMessage
            id="pages.forgotPassword.reset.success.description"
            defaultMessage="您的密码已成功重置，现在可以使用新密码登录了"
          />
        }
        type="success"
        showIcon
      />
      <Button
        type="primary"
        onClick={() => history.push('/user/login')}
        size="large"
        style={{ marginTop: 24 }}
      >
        <FormattedMessage id="pages.forgotPassword.goToLogin" defaultMessage="前往登录" />
      </Button>
    </div>
  );

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.header}>
          <Title level={2} className={styles.title}>
            <FormattedMessage id="pages.forgotPassword.title" defaultMessage="忘记密码" />
          </Title>
          <Text type="secondary" className={styles.description}>
            <FormattedMessage
              id="pages.forgotPassword.description"
              defaultMessage="通过手机号找回您的密码"
            />
          </Text>
        </div>

        <Steps
          current={currentStep}
          items={steps}
          className={styles.steps}
          direction="horizontal"
        />

        <div className={styles.formContainer}>
          {success ? (
            <div className={styles.successContainer}>
              <Alert
                message={
                  <FormattedMessage
                    id="pages.forgotPassword.reset.success"
                    defaultMessage="密码重置成功"
                  />
                }
                description={
                  <FormattedMessage
                    id="pages.forgotPassword.reset.success.description"
                    defaultMessage="您的密码已成功重置，现在可以使用新密码登录了"
                  />
                }
                type="success"
                showIcon
              />
              <Button
                type="primary"
                onClick={() => history.push('/user/login')}
                size="large"
                block
                style={{ marginTop: 24 }}
              >
                <FormattedMessage id="pages.forgotPassword.goToLogin" defaultMessage="前往登录" />
              </Button>
            </div>
          ) : (
            <>
              {currentStep === 0 && renderStep0()}
              {currentStep === 1 && renderStep1()}
              {currentStep === 2 && renderStep2()}

              {currentStep > 0 && currentStep < 2 && (
                <div style={{ textAlign: 'center', marginTop: 16 }}>
                  <Button onClick={() => setCurrentStep(currentStep - 1)}>
                    <FormattedMessage id="pages.forgotPassword.previous" defaultMessage="上一步" />
                  </Button>
                </div>
              )}
            </>
          )}
        </div>

        {currentStep !== 2 && (
          <div className={styles.footer}>
            <a onClick={() => history.push('/user/login')}>
              <FormattedMessage id="pages.login.backToLogin" defaultMessage="返回登录" />
            </a>
          </div>
        )}
      </div>
    </div>
  );
};
export default Index;
